import axios from "axios";
import {Message} from 'element-ui'

console.log('SSO_URL', API.SSO_URL);

//创建axios实例
const instance = axios.create({
	// `headers` 请求头的通用配置
	headers: {
		// 'X-Requested-With': 'XMLHttpRequest'
	},
	timeout: 0, // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
	withCredentials: false, // `withCredentials` 表示跨域请求时是否需要使用凭证
});

// 请求拦截器
instance.interceptors.request.use(
	config => {
		// 可以根据不同请求，设置不同的Content-Type
		return config;
	},
	error => {
		//错误处理...
		return Promise.reject(error);
	}
);

// 响应拦截器
instance.interceptors.response.use(
	response => {
		console.log(response);
		if(response.data.code == 200 || response.data.statusCode == 0) { //根据业务code来处理错误
			return response;
		} else {
			Message.error(response.data.msg) //错误消息提示
			return Promise.reject(response);
		}
	},
	error => {
		console.log(error);
		if(error.response.status == 302) { //根据http状态处理错误
			//token失效，跳转SSO登录
			// window.location.href = "http://130.130.0.201:7070/#/login?response_type=code&client_id=EIP&redirect_uri=http://130.130.0.201:20000/home";
			window.location.href = `${API.SSO_URL}?response_type=code&client_id=EIP&redirect_uri=${API.EIIP_URL}`;
		}
		return Promise.reject(error);
	}
);

function request(config) {
	//login接口不携带token，否则后端会莫名返回403，后端问题依然在排查中
	if(config.url.indexOf('/login') == -1) {
		if(config.headers) {
			config.headers['eiip-token'] = sessionStorage.getItem("eiip-token")
			config.headers['sso-token'] = sessionStorage.getItem("sso-token")
		} else {
			config.headers = { 
				'eiip-token' : sessionStorage.getItem("eiip-token") ,
				'sso-token' : sessionStorage.getItem("sso-token") 
			}
		}
	}
	return instance.request(config);
}

function jsonp(url, jsonp='callback') {
	if (!window) console.error('当前为非浏览器环境，发送jsonp失败');
	return new Promise((resolve, reject) => {
		let _script = document.createElement('script');
		_script.type = 'text/javascript';
		let _callbackFunctionName = '__axios__yt__callback'+Date.now();
		_script.src = (/\?[^=]+=/.test(url)) ? (url+'&'+jsonp+'='+_callbackFunctionName) : (url+'?'+jsonp+'='+_callbackFunctionName)
		 
		window[_callbackFunctionName] = (result) => {
			resolve(result);
			document.getElementsByTagName('head')[0].removeChild(_script); //删除临时script标签
			window[_callbackFunctionName] = null; //删除临时回调
		}
		document.getElementsByTagName('head')[0].appendChild(_script);
	})
}
export {request, jsonp}
